//
//  LoginViewController.swift
//  FMRadio
//
//  Created by 范东 on 2022/7/26.
//

import UIKit
import FDUIKit
import AuthenticationServices
import FDNetwork
import Toast

class LoginViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        view.addSubview(loginBtn)
        loginBtn.snp.makeConstraints { make in
            make.bottom.equalToSuperview().offset(-CGFloat.safeAreaBottomHeight-44)
            make.left.equalToSuperview().offset(44)
            make.right.equalToSuperview().offset(-44)
            make.height.equalTo(44)
        }
        
        view.addSubview(skipBtn)
        skipBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-20)
            make.top.equalToSuperview().offset(20)
        }
    }
    
    @objc func loginBtnAction(){
        let provider = ASAuthorizationAppleIDProvider()
        let request = provider.createRequest()
        request.requestedScopes = [.fullName,.email]
        let authC = ASAuthorizationController(authorizationRequests: [request])
        authC.delegate = self
        authC.presentationContextProvider = self
        authC.performRequests()
    }
    
    @objc func skipBtnAction(){
        dismiss(animated: true, completion: nil)
    }
    
    lazy var loginBtn:ASAuthorizationAppleIDButton  = {
        let loginBtn = ASAuthorizationAppleIDButton(authorizationButtonType: .signIn, authorizationButtonStyle: .black)
        loginBtn.addTarget(self, action: #selector(loginBtnAction), for: .touchUpInside)
        return loginBtn
    }()
    
    lazy var skipBtn: UIButton = {
        let skipBtn = UIButton(type: .custom)
        skipBtn.setTitle("以后再说", for: .normal)
        skipBtn.setTitleColor(.gray, for: .normal)
        skipBtn.titleLabel?.font = .systemFont(ofSize: 15)
        skipBtn.addTarget(self, action: #selector(skipBtnAction), for: .touchUpInside)
        return skipBtn
    }()

}

extension LoginViewController: ASAuthorizationControllerDelegate,ASAuthorizationControllerPresentationContextProviding{
    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
        FMRadio.getCurrentWindow()
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {
        if authorization.credential.isKind(of: ASAuthorizationAppleIDCredential.classForCoder()) {
            let credential = authorization.credential as! ASAuthorizationAppleIDCredential
//            let state = credential.state
            let user = credential.user
//            let fullName = credential.fullName
//            let email = credential.email
//            let authorizationCode = String(data: credential.authorizationCode!, encoding: .utf8)
//            let identityToken = String(data: credential.identityToken!, encoding: .utf8)
//            let realUserStatus = credential.realUserStatus
            FDNetwork.GET(url: .serverURL, param: ["s":"App.User_User.Login","username":user,"password":"123456"]) { result in
                let resultDict = result as! [String: Any]
                let data = resultDict["data"] as! [String: Any]
                let ret = resultDict["ret"] as! Int
                if ret == 400 {
                    FDNetwork.GET(url: .serverURL, param: ["s":"App.User_User.Register","username":user,"password":"123456"]) { result2 in
                        let resultDict2 = result2 as! [String: Any]
                        let data2 = resultDict2["data"] as! [String: Any]
                        let user_id2 = data2["user_id"] as! Int
                        FDNetwork.GET(url: .serverURL, param: ["s":"App.User_User.Login","username":user,"password":"123456"]) { result3 in
                            let resultDict3 = result3 as! [String: Any]
                            let data2 = resultDict3["data"] as! [String: Any]
                            FMRadio.saveUser(dict: data2)
                            let userSig = data2["userSig"] as! String
                            self.login(userID: user_id2, userSig: userSig)
                        } failure: { error in
                            self.view.makeToast(error)
                        }
                    } failure: { error in
                        self.view.makeToast(error)
                    }
                }else{
                    FMRadio.saveUser(dict: data)
                    let user_id = data["user_id"] as! Int
                    let userSig = data["userSig"] as! String
                    self.login(userID: user_id, userSig: userSig)
                }
            } failure: { error in
                self.view.makeToast(error)
            }
        }
    }
    
    func login(userID: Int, userSig: String){
        TUILogin.login(Int32(SDKAPPID), userID: String(userID), userSig: userSig) {
            //加入全员大群
            V2TIMManager.sharedInstance().joinGroup(.FullGroupId, msg: "加入全员大群") {
                debugPrint("加入全员大群成功")
            } fail: { code, msg in
                debugPrint("加入全员大群失败 code:"+"\(code)"+"msg:"+(msg ?? ""))
            }
            self.dismiss(animated: true, completion: nil)
        } fail: { code, msg in
            self.view.makeToast(msg)
        }
        
    }
    
    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
        var errorMsg = ""
        switch (error as NSError).code {
        case ASAuthorizationError.canceled.rawValue:
            errorMsg = "已取消"
            break
        case ASAuthorizationError.failed.rawValue:
            errorMsg = "授权失败"
            break
        case ASAuthorizationError.invalidResponse.rawValue:
            errorMsg = "响应无效"
            break
        case ASAuthorizationError.notHandled.rawValue:
            errorMsg = "未能处理授权"
            break
        case ASAuthorizationError.unknown.rawValue:
            errorMsg = "未知错误"
            break
        default:
            break
        }
        self.view.makeToast(errorMsg)
    }
}
